<template>
  <nav-bar title="指定承运人"></nav-bar>
  <div class="main">
    <div class="main_top">
      <!-- <van-radio-group v-model="carrierType" direction="horizontal" class="radio" @change="onSearch">
        <van-radio name="1">承运商</van-radio>
        <van-radio name="2">司机</van-radio>
      </van-radio-group> -->
      <div class="radio">
        <div class="radio_item" :class="carrierType === '1' && 'radio_item_active'" @click="onChangeRadio('1')">
          <span>承运商</span>
        </div>
        <div class="radio_item" :class="carrierType === '2' && 'radio_item_active'" @click="onChangeRadio('2')">
          <span>司机</span>
        </div>
      </div>
    </div>
    <van-search v-model="searchVal" placeholder="输入承运人的姓名或手机号码" @update:model-value="getList">
      <template #left-icon>
        <img src="../../assets/image/waybill/search.png" alt="" class="magnifier" />
      </template>
    </van-search>
    <div class="common" v-show="!searchVal && list.length > 0">{{ `常用${carrierText}` }}</div>
    <van-list :finished="finished" finished-text="没有更多了">
      <van-swipe-cell :right-width="searchVal ? '0' : '58'" v-for="(item, index) in list" :key="index">
        <div class="item">
          <div class="authentication" :class="item.status === 2 && 'failure'">
            {{ item.status === 2 ? '已失效' : '已认证' }}
          </div>
          <div class="grade">
            <span class="grade_num">{{ carrierText }}评价 {{ item.grade.toFixed(1) }}</span>
            <!-- <van-rate v-model="item.grade" color="#FFCA2C" size="12px" readonly /> -->
          </div>
          <div class="item_top" @click="onDetail(item.id)">
            <img :src="carrierType === '1' ? carrier_header : driver_header" class="photo" />
            <div class="">
              <div class="name">{{ item.name }}</div>
              <div class="phone">{{ item.phone }}</div>
            </div>
          </div>
          <div class="item_bottom">
            <div class="add_common">
              <van-checkbox v-model="item.checked" v-show="searchVal && !item.isCarrier">
                <template #icon="props">
                  <svg-icon :name="props.checked ? 'selected2' : 'select2'"></svg-icon>
                  <span class="common_text">添加常用承运人</span>
                </template>
              </van-checkbox>
              <span class="common_text" v-show="item.isCarrier">已添加常用承运人</span>
            </div>
            <div>
              <van-button type="primary" class="button_left" @click="goTelphone(item.phone)">联系他</van-button>
              <van-button type="primary" class="button_right" :disabled="item.status === 2" @click="assignOrder(item)">
                {{ `指定${carrierText}` }}
              </van-button>
            </div>
          </div>
        </div>
        <template #right>
          <div class="delete" @click="deleteCommonCarrier(item.id)">
            <svg-icon name="delete"></svg-icon>
          </div>
        </template>
      </van-swipe-cell>
    </van-list>
  </div>
  <PhonePopup :isShow="isTelPhoneShow" :telNumber="telNumber" @cancel_show="isTelPhoneShow = false" />
  <van-popup v-model:show="passwordPoppup" position="bottom" class="selfPopup">
    <div class="passwordPoppup">
      <div class="memo">请输入支付密码</div>
      <van-password-input :value="payPassword" :focused="true" />
      <van-number-keyboard
        v-model="payPassword"
        :show="true"
        @input="prePayType"
        maxlength="6"
        @blur="passwordPoppup = false"
      />
    </div>
  </van-popup>
</template>

<script lang="ts">
import navBar from '@/components/NavBar.vue'
import { reactive, toRefs, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import PhonePopup from '@/components/PhonePopup.vue'
import { api } from '@/http/api'
import http from '@/http'
import store from '@/store/index'
import { Toast } from 'vant'
import driver_header from '@/assets/image/driver_header.png'
import carrier_header from '@/assets/image/carrier_header.png'
import SvgIcon from '@/components/SvgIcon.vue'
import { UserTypesEm } from '@/store/enums'

export default {
  name: 'AssignOrder',
  components: {
    navBar,
    PhonePopup,
    SvgIcon
  },
  setup() {
    const route = useRoute(),
      router = useRouter()
    let params: any = {}

    if (route.params && route.params.id) {
      params = { id: route.params.id }
    } else if (route.params && route.params.params) {
      params = JSON.parse(route.params.params as string)
      params.pointType = 1
    }
    console.log(params)
    const state = reactive({
      list: [] as any[],
      searchVal: '',
      carrierType: '1',
      carrierText: '承运商',
      isTelPhoneShow: false,
      finished: false,
      telNumber: '' as number | string,
      passwordPoppup: false,
      payPassword: '',
      item: {} as any
    })

    const onChangeRadio = (type: string) => {
      state.carrierType = type
      state.carrierText = type === '1' ? '承运商' : '司机'
      getList()
    }

    const getList = () => {
      if (state.searchVal) {
        onSearch()
      } else {
        getCommonCarrier()
      }
    }

    //获取常用承运人列表
    const getCommonCarrier = () => {
      state.finished = false
      http<string>({
        url: api.getCommonCarrier,
        method: 'get',
        params: { paged: 1, userType: state.carrierType === '1' ? 3 : 4 }
      }).then((res: any) => {
        const arr: any[] = []
        state.list = []
        if (res.rows.length > 0) {
          state.finished = true
          res.rows.map((item: any) => {
            arr.push({
              name: item.userName,
              phone: item.userPhone,
              status: item.status,
              id: item.userId,
              grade: item.grade,
              plateNo: item.plateNo ? item.plateNo : ''
            })
          })
        }
        state.list = [...arr]
      })
    }

    const onSearch = () => {
      let url = ''
      if (state.carrierType === '1') {
        url = api.carrierSearchList
      } else {
        url = api.driverSearchList
      }
      state.finished = false
      http<string>({
        url,
        method: 'get',
        params: { name: state.searchVal, auditStatus: '2', filterType: '1' }
      }).then((res: any) => {
        if (res && res.length > 0) {
          state.finished = true
        }
        state.list = res
      })
    }

    //联系他
    const goTelphone = (telNumber: number) => {
      state.telNumber = telNumber
      state.isTelPhoneShow = true
    }

    //预付时弹出输入支付密码
    const prePayType = (value: string) => {
      const password: string = state.payPassword + value
      const { url, currentParams } = handleData()
      if (password.length === 6) {
        //校验支付密码
        http<string>({
          url: api.payPasswordCheck,
          method: 'get',
          params: { payPassword: password }
        }).then((res: any) => {
          if (res) {
            //生成订单
            http<string>({
              url: url,
              method: 'post',
              data: Object.assign(params, currentParams, { carrierType: state.carrierType })
            }).then((res: any) => {
              //扣款
              http<string>({
                url: api.transportOrderPayment,
                method: 'post',
                data: { orderId: res, password }
              }).then(() => {
                router.push({ name: 'Waybill' })
                store.commit('cachedView/clearCachedItem', { name: 'Delivery' })
                store.commit('cachedView/clearCachedItem', { name: 'DeliveryInfo' })
                Toast.success('发货成功')
                if (state.item.checked) addCommonCarrier(state.item)
                state.passwordPoppup = false
              })
            })
          } else {
            Toast.fail('支付密码错误')
          }
        })
      }
    }
    //整理数据
    const handleData = () => {
      const item = state.item
      let currentParams: any = {}
      if (params.id) {
        currentParams = {
          pointId: item.id,
          name: item.name,
          mobile: item.phone,
          plateNo: item.plateNo
        }
      } else {
        if (state.carrierType === '1') {
          currentParams = {
            carrierId: item.id,
            carrierName: item.name,
            carrierMobile: item.phone
          }
        } else {
          currentParams = {
            driverId: item.id,
            driverName: item.name,
            driverMobile: item.phone,
            plateNo: item.plateNo
          }
        }
      }
      const url = params.id ? api.orderPoint : api.transportOrderAdd
      const carrierType = params.id ? { type: state.carrierType } : { carrierType: state.carrierType }
      return { url, currentParams, carrierType }
    }

    //指派订单给承运商或司机
    const assignOrder = (item: any) => {
      state.item = item
      const { url, currentParams, carrierType } = handleData()
      // if (params.payType === '1') {
      //   // 显示密码输入框
      //   state.passwordPoppup = true
      // } else {
      http<string>({
        url: url,
        method: 'post',
        data: Object.assign(params, currentParams, carrierType)
      }).then((res: any) => {
        store.commit('cachedView/clearCachedItem', { name: 'Delivery' })
        store.commit('cachedView/clearCachedItem', { name: 'DeliveryInfo' })
        Toast.success('指派成功')
        if (state.item.checked) {
          addCommonCarrier(state.item)
        } else {
          router.push({ name: 'Waybill' })
        }
      })
      // }
    }

    //添加常用承运人列表
    const addCommonCarrier = (item: any) => {
      const obj = {
        userId: item.id,
        userName: item.name,
        userPhone: item.phone,
        userType: state.carrierType === '1' ? 3 : 4
      }
      http<string>({
        url: api.commonCarrierAdd,
        method: 'post',
        data: obj
      }).then(() => {
        router.push({ name: 'Waybill' })
      })
    }

    //删除常用承运人列表
    const deleteCommonCarrier = (id: string) => {
      http<string>({
        url: api.commonCarrierDelete,
        method: 'post',
        data: { id }
      }).then(() => {
        getList()
      })
    }

    // 司机/承运人简介
    const onDetail = (userId: string): void => {
      let userType: number | string = ''
      if (state.carrierType === '1') {
        // 承运人
        userType = UserTypesEm.CARRIER.value
      } else {
        // 司机
        userType = UserTypesEm.DRIVER.value
      }

      router.push({
        name: 'Introduce',
        query: { userType, userId }
      })
    }

    onMounted(() => {
      getList()
    })

    return {
      ...toRefs(state),
      getList,
      goTelphone,
      assignOrder,
      onChangeRadio,
      prePayType,
      deleteCommonCarrier,
      driver_header,
      carrier_header,
      onDetail
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/style/variables.scss';
@import '@/style/mixins.scss';
.main {
  width: 100%;
  min-height: $main-min-height;
  background: $background-color-base;
  padding-top: 44px;
  box-sizing: border-box;
  position: relative;

  ::v-deep(.van-search__content) {
    padding: 0;
    background: none;
    box-shadow: 0px 0px 14px 4px rgba(185, 185, 185, 0.1);
    border-radius: 25px;
  }

  ::v-deep(.van-cell) {
    background: #fff;
    padding: 11px 8px;
    border-radius: 25px;
  }
  ::v-deep(.van-search) {
    background: none;
    margin-top: 20px;
    margin-bottom: 15px;
    padding: 0 12px;
  }

  .magnifier {
    vertical-align: middle;
    width: 20x;
    height: 20px;
    margin-right: 12px;
  }
  .main_top {
    position: fixed;
    width: 100%;
    top: 88px;
    left: 0;
    z-index: 1;
    box-shadow: 0px -1px 2px 0px rgba(233, 233, 233, 0.5);
    > .radio {
      width: 100%;
      height: 44px;
      line-height: 44px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      background: #fff;
      > .radio_item {
        height: 100%;
        width: 50%;
        text-align: center;
        font-size: 14px;
        color: $color-text-secondary;
        span {
          display: inline-block;
          box-sizing: border-box;
          height: 44px;
        }
      }
      .radio_item_active {
        color: $color-primary-light-1;
        span {
          border-bottom: 3px solid $color-primary-light-1;
        }
      }
    }
  }
  .common {
    color: $color-text-regular;
    margin: 17px 0 13px 22px;
  }
  .delete {
    width: 46px;
    height: 46px;
    line-height: 46px;
    background: #ffffff;
    box-shadow: 0px 4px 8px 0px rgba(143, 143, 143, 0.11);
    border-radius: 23px;
    margin-top: 45px;
    margin-left: -2px;
    text-align: center;
    .icon-delete {
      width: 18px;
      height: 18px;
    }
  }
  .item {
    width: 351px;
    height: 129px;
    background: #ffffff;
    box-shadow: 0px 6px 14px 0px rgba(221, 221, 221, 0.15);
    border-radius: 8px;
    margin: 0 12px 15px 12px;
    padding: 10px 10px 0 10px;
    box-sizing: border-box;
    position: relative;
    > .authentication {
      width: 82px;
      height: 32px;
      border-radius: 2px;
      background: rgba(255, 0, 79, 0.02);
      border: 1px solid rgba(255, 0, 79, 0.5);
      color: #ff004f;
      text-align: center;
      line-height: 34px;
      position: absolute;
      top: 0px;
      right: -7px;
      font-size: 22px;
      transform: scale(0.5);
    }
    > .grade {
      position: absolute;
      top: 36px;
      right: 15px;
      display: flex;
      align-items: center;
      .grade_num {
        color: $color-text-regular;
        margin-right: 5px;
        font-size: 12px;
      }
    }
    .failure {
      background: rgba(159, 162, 175, 0.1);
      border: 1px solid rgba(159, 162, 175, 0.3);
      color: #9fa2af;
    }
    > .item_top {
      display: flex;
      align-items: flex-start;
      justify-content: flex-start;
      height: 55px;
      padding-bottom: 9px;
      box-sizing: border-box;
      position: relative;
      &::after {
        @include px-1;
      }
      .photo {
        width: 28px;
        height: 28px;
        border-radius: 50%;
        // border: 1px solid rgba(240, 240, 240, 0.99);
        margin-right: 10px;
      }
      .name {
        color: $color-text-regular;
        line-height: 20px;
        margin-bottom: 7px;
      }
    }
    .item_bottom {
      height: 63px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      > .add_common {
        .svg-icon {
          width: 16px;
          height: 16px;
          margin-right: 5px;
        }
        .common_text {
          font-size: 12px;
          color: $color-text-primary;
        }
      }
      .button_left {
        width: 94px;
        height: 32px;
        border-radius: 17px;
        border: 1px solid $color-primary;
        background: #fff;
        color: $color-primary;
        margin-right: 10px;
      }
      .button_right {
        height: 32px;
        border-radius: 17px;
      }
    }
  }
}
.passwordPoppup {
  width: 100%;
  padding-top: 30px;
  height: 355px;
  .memo {
    text-align: center;
    font-size: 14px;
    margin-bottom: 10px;
    color: #333;
  }
}
</style>
